<template>
  <div
    v-loading="loading"
    style="display: flex; flex-direction: column; flex: 1; height: 100%"
    element-loading-text="加载中..."
  >
    <div class="header" v-if="detail">
      <div class="text">
        <span class="text_title">
          <span style="font-size: 14px; font-weight: bold; margin-right: 5px">{{
            detail.name
          }}</span>
          <HStatus type="warning" v-if="detail.status === 1">待审核</HStatus>
          <HStatus v-if="detail.status === 2">使用中</HStatus>
          <HStatus type="error" v-if="detail.status === 3">已驳回</HStatus>
          <HStatus type="info" v-if="detail.status === 4">已禁用</HStatus>
        </span>
        <p style="padding: 5px 0">结算类型：{{ detail.settlementType == 1 ? '预充值' : '月付' }}</p>
      </div>
      <div style="display: flex; gap: 5px">
        <HPlainButton @click="goEditDetails(detail.id)">编辑</HPlainButton>
        <HPlainButton
          type="success"
          v-if="detail.status == 1"
          @click="checkFactoryType(detail.id, 1)"
          >通过</HPlainButton
        >
        <HPlainButton type="error" v-if="detail.status == 1" @click="checkFactoryType(detail.id, 2)"
          >驳回</HPlainButton
        >
        <HPlainButton type="error" v-if="false" style="width: 60px">删除</HPlainButton>
      </div>
    </div>
    <ul class="list" v-if="detail">
      <li>
        <p class="title">账户余额</p>
        <div class="xy_money">
          <div class="xy_sentent" style="display: flex; gap: 5px; align-items: baseline">
            <div>
              <span class="xy_mo">
                ￥{{ detail.money.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') }}
              </span>
              元
            </div>
            <HPlainButton @click="ChangeMoney" :padding-lr="4" :height="22">
              调整余额
            </HPlainButton>
          </div>
          <div class="xy_tip">
            <p>
              <span>
                {{ detail.freezeMoney.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,') }}
              </span>
              元
            </p>
            <p v-if="detail.status === 2">冻结金额</p>
            <p v-if="detail.status === 1">占用金额</p>
          </div>
          <div class="xy_tip">
            <p>
              <span>
                {{
                  (detail.money - detail.freezeMoney)
                    .toFixed(2)
                    .replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
                }}
              </span>
              元
            </p>
            <p>可下单金额</p>
          </div>
        </div>
      </li>
      <li>
        <p class="title">总工单</p>
        <div class="xy_money">
          <div class="xy_sentent">
            <div>
              <span class="xy_mo">
                {{ detail.totalOrderCount.toLocaleString() }}
              </span>
            </div>
          </div>
          <div class="xy_tip">
            <p>
              <span>
                {{ detail.handlerOrderCount.toLocaleString() }}
              </span>
            </p>
            <p>处理中</p>
          </div>
          <div class="xy_tip">
            <p>
              <span>
                {{ detail.waitSettlementOrderCount.toLocaleString() }}
              </span>
            </p>
            <p>待结算</p>
          </div>
        </div>
      </li>
    </ul>

    <TablePane v-if="detail" :factory-detail="detail" @loading-change="loading = $event" />

    <!-- 调整金额 -->
    <HModal
      title="调整金额"
      :model-value="assignDialog"
      @close="onUpdateMoneyModalCancelClick"
      width="auto"
    >
      <div element-loading-text="加载中...">
        <el-form
          ref="formRef"
          :rules="rulesForm"
          :model="adjustVo"
          label-position="right"
          label-width="auto"
          @validate="handleUpdateMoneyFormValidate"
        >
          <div class="update_money_modal_form_content">
            <el-form-item label="当前余额">
              <el-input v-model="detail.money" disabled class="input_w" clearable>
                <template #prepend>￥</template></el-input
              >
            </el-form-item>

            <el-form-item
              label="调整方式"
              prop="adjustMode"
              :class="{ validate_fail: !updateMoneyModalFormValidateResult['adjustMode'] }"
            >
              <el-radio-group v-model="adjustVo.adjustMode">
                <el-radio :value="1">增加</el-radio>
                <el-radio :value="2">减少</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item
              label="调整额度"
              prop="adjustMoney"
              :class="{ validate_fail: !updateMoneyModalFormValidateResult['adjustMoney'] }"
            >
              <el-input
                v-model="adjustVo.adjustMoney"
                class="input_w"
                placeholder="请输入额度"
                clearable
                @keyup="handleInputMoney"
              >
                <template #prepend>￥</template>
              </el-input>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="adjustVo.remark"
                type="textarea"
                clearable
                placeholder="请输入备注"
                resize="both"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </div>
        </el-form>
      </div>
      <template #footerRight>
        <HButton is-modal type="primary" @click="onSave">保存</HButton>
        <HButton is-modal @click="onUpdateMoneyModalCancelClick">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { ElMessage, ElMessageBox, FormItemProp } from 'element-plus'
  import { useRoute, useRouter } from 'vue-router'
  import TablePane from './TablePane.vue'
  import { getFactoryDetail, checkFactory, saveFactoryAdjustMoney } from '@/api/merchant'
  import { checkNum } from '@/utils/validate'
  import { FactoryDetail } from './types'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.merchant.merchantDetail,
  })

  const router = useRouter()
  const route = useRoute()
  const detail = ref<FactoryDetail | null>(null) //详情
  const loading = ref(false)
  const assignDialog = ref(false)
  const formRef = ref()
  const adjustVo = ref({
    adjustMode: 1, //	调整方式：1-增加，2-减少,示例值(1)
    adjustMoney: '', //调整金额
    remark: '', //	备注
  })
  const rulesForm = ref({
    adjustMode: [{ required: true, message: '调整方式', trigger: ['blur', 'change'] }],
    adjustMoney: [{ required: true, message: '调整金额', trigger: ['blur', 'change'] }],
    remindMode: [{ required: true, message: '提醒方式', trigger: ['blur', 'change'] }],
  })

  const updateMoneyModalFormValidateResult = ref({
    adjustMode: true,
    adjustMoney: true,
  })

  const handleUpdateMoneyFormValidate = (prop: FormItemProp, isValid: boolean) => {
    updateMoneyModalFormValidateResult.value[prop as string] = isValid
  }

  // 取消弹窗
  const onUpdateMoneyModalCancelClick = () => {
    assignDialog.value = false
    updateMoneyModalFormValidateResult.value = {
      adjustMode: true,
      adjustMoney: true,
    }
  }

  // 金额输入事件
  const handleInputMoney = (event: Event) => {
    checkNum(event)

    // 解决多次输入小数会保留三位的情况
    adjustVo.value.adjustMoney = (event.target as HTMLInputElement).value

    // 限制整数位只能是8位
    let value = (event.target as HTMLInputElement).value
    let index = (event.target as HTMLInputElement).value.indexOf('.')
    if (index > -1) {
      // 包含小数点
      if (value.length > 11) {
        // 截取前8位整数
        const integer = value.substring(0, 8)

        // 截取小数和小数点
        const decimal = value.substring(index)
        ;(event.target as HTMLInputElement).value = `${integer}${decimal}`
      }
    } else {
      // 不包含小数点
      ;(event.target as HTMLInputElement).value = value.substring(0, 8)
    }
  }

  // 保存金额调整
  const onSave = () => {
    if (!formRef.value) return
    formRef.value.validate((valid) => {
      if (valid) {
        saveFactoryAdjustMoney(adjustVo.value, route.params.id).then((res) => {
          if (res) {
            if (res.data.success) {
              assignDialog.value = false
              getNetworkDetail()
              adjustVo.value = {
                adjustMode: 1,
                adjustMoney: '',
                remark: '',
              }
            }
            if (res.data.isError)
              ElMessage({
                showClose: true,
                message: res.data.message,
                type: res.data.success ? 'success' : 'error',
                duration: 3000,
              })
          }
        })
      }
    })
  }
  const ChangeMoney = () => {
    assignDialog.value = true
  }
  // 获取详情
  const getNetworkDetail = async () => {
    if (!route.params.id) return
    loading.value = true
    const res = await getFactoryDetail(route.params.id)
    if (res.data.success) {
      detail.value = res.data.data.row
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 3000,
        })
    }
    loading.value = false
  }
  // 审核商家
  async function checkFactoryType(id: string, type) {
    ElMessageBox({
      title: '提示',
      message: type == 1 ? `确认审核通过?` : '确认驳回？',
      showCancelButton: true,
      closeOnClickModal: false,
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
    })
      .then(async () => {
        loading.value = true

        const res = await checkFactory(id, type)
        if (res.data.success) {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'success',
          })
          getNetworkDetail()
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
            })
        }
        loading.value = false
      })
      .catch()
  }
  const goEditDetails = (id: string) => {
    router.push(`/merchant/newdetail/${id}`)
  }
  onMounted(() => {
    getNetworkDetail()
  })
</script>

<style scoped lang="scss">
  @import './index';
</style>
